﻿// Write a program that replaces all occurrences of the substring "start" with the substring "finish" in a text file.
// Ensure it will work with large files (e.g. 100 MB).

using System;
using System.IO;
using System.Text.RegularExpressions;

class ReplaceSubstringInTextFile
{
    enum ReplaceType
    {
        Substring,
        Word
    }

    static void Main()
    {
        string path = @"..\..\";

        string inputFileName = "file.txt";
        string inputFile = Path.Combine(path, inputFileName);

        try
        {
            string findWhat = "start";
            string replaceWith = "finish";
            ReplaceTextInFile(inputFile, findWhat, replaceWith, ReplaceType.Substring);
            Console.WriteLine("All substrings '{0}' in file '{2}' are replaced with '{1}'", findWhat, replaceWith, inputFileName);
        }
        catch (Exception exc)
        {
            Console.WriteLine(exc.Message);
        }
    }

    static void ReplaceTextInFile(string inputFile, string findWhat, string replaceWith, ReplaceType type)
    {
        string outputFileName = "temp.txt";
        string path = Path.GetDirectoryName(inputFile);
        string outputFile = Path.Combine(path, outputFileName);

        using (FileStream fileStream = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (BufferedStream bufferedStream = new BufferedStream(fileStream))
        using (StreamReader reader = new StreamReader(bufferedStream))
        using (StreamWriter writer = new StreamWriter(outputFile))
        {
            while (!reader.EndOfStream)
            {
                string currentLine = reader.ReadLine();
                if (type.Equals(ReplaceType.Substring))
                {
                    currentLine = currentLine.Replace(findWhat, replaceWith);
                }
                else
                {
                    string findWhatRegex = string.Format(@"\b{0}\b", findWhat);
                    currentLine = Regex.Replace(currentLine, findWhatRegex, replaceWith);
                }

                writer.WriteLine(currentLine);
            }
        }

        File.Replace(outputFile, inputFile, Path.ChangeExtension(inputFile, ".bak"));
    }
}